<!-- /*
 * @Author: 谢力 843926058@qq.com
 * @Date:   2019-11-06
 * @Last Modified by:   谢力
 * @Last Modified time: 2019-11-07
 */ -->
<template>
    <div class="ui-mode-container ui-mode-box flex-col">
        <div class="ui-header-item gradient">
            <div class="ui-header-arraw prev" @click="handleHistory" @touchstart.stop>
                <i class="iconfont icon iconjiantou-zuo-cuxiantiao"></i>
            </div>
            <div class="ui-header-title">APP图片上传功能</div>
            <div class="ui-header-arraw next flex-row align-center" @touchstart.stop @click="handleHome">
                <i class="iconfont icon iconi-home"></i>
            </div>
        </div>
        <div class="ui-mode-content flex1" ref="scroll">
            <template v-if="pageStatus">
                <div class="box mar-bottom-5">
                    <p class="title">图片上传功能演示</p>
                    <div class="inner">
                        <div class="ms-wrap-upload mt-flex align-center-row flex-wrap" style="padding:0 0.85rem .42rem 0.85rem">
                            <template v-if="bannerList&&bannerList.length">
                                <div class="ms-item-upload compalte"
                                    :key="k"
                                    v-for="(item,k) in bannerList">
                                    <div class="ms-upload-box flex-row align-center">
                                        <span class="ms-upload-text"></span>
                                        <img :src="item">
                                        <input type="hidden" name="goods_main_image_file" class="ms-upload-file"/>
                                        <input type="hidden" name="goods_main_image"/>
                                    </div>
                                    <span class="ms-upload-close" @click.stop="deleteItem(i,k)"></span>
                                    <i class="mt-loading-icon mt-rotate-load ms-upload-loading"></i>
                                </div>
                            </template>
                            <template v-if="bannerList.length<4">
                                <label class="ms-item-upload" :for="'upload-pic'+i">
                                    <div class="ms-upload-box flex-row align-center">
                                        <span class="ms-upload-text"></span>
                                    </div>
                                    <span class="ms-upload-close"></span>
                                    <i class="mt-loading-icon mt-rotate-load ms-upload-loading"></i>
                                </label>
                                <input :id="'upload-pic'+i" style="display:none" accept="image/gif, image/jpeg, image/png, image/jpg" @change='add_file($event,i)' type="file">
                            </template>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>
</template>
<script>
import mixinCommon from '@/views/content/mixins/common';
import mixinRequest from '@/views/content/mixins/request';
import mixinShare from '@/views/content/mixins/share';
import mobileUpload from "@/components/mobileUpload";
// 引入LocalStorage
import {LocalStorage} from "@/utils/storage";
export default {
    name: 'my',
    data(){
        return {
            public_agent_info:{},
            public_user_info:{},
            imgLimit1:1,//上传图片最大值
            bannerList: [],//上传的图片数组
            warnTxt1:'图片宽高比为 1:1,建议大小100kb左右',//上传组件右侧建议
        };
    },
    mixins:[
        mixinCommon,
        mixinRequest,
        mixinShare
    ],
    components:{
        mobileUpload
    },
    computed:{
    },
    watch:{
        resourceLoaded:{
            handler(flag){
                flag&&this.$nextTick(this.init);
            },
            immediate:true
        }
    },
    created(){
    },
    mounted(){
    },
    methods:{
        /*
         * 初始化
         */
        init(){
            let public_agent_info=this.$store.state.global.public_agent_info,
                public_user_info=this.$store.state.global.public_user_info;
            if(public_agent_info&&public_user_info){
                this.public_agent_info=public_agent_info;
                this.public_user_info=public_user_info;
                document.title=this.public_agent_info.application_name;
                this.showContent();
            }else{
                this.getPageInfo({
                    name:'my',
                    param:{
                        invoke_method:'user_and_shop_info'
                    }
                }).then(({result,response})=>{
                    this.public_agent_info=result.public_agent_info||{};
                    this.public_user_info=result.public_user_info||{};
                    document.title=this.public_agent_info.application_name;
                    this.setState({
                        key:'public_agent_info',
                        value:this.public_agent_info
                    });
                    this.setState({
                        key:'public_user_info',
                        value:this.public_user_info
                    });
                });
            };
        },
        /*
         * 请求失败刷新
         */
        handleRefresh(){
            this.init();
        },
        /*
         * 上传图片
         */
        add_file(event){ 
            var targetEle=event.target;
            this.changeLoading=this.$$loading({
                text:' ',
                target:document.getElementsByClassName('ms-upload-box')[document.getElementsByClassName('ms-upload-box').length-1],
                masterBackground:'rgba(0,0,0,0.6)',
                boxBackground:'rgba(0,0,0,0)',
            });
            targetEle.setAttribute('disabled','disabled');
            if(event.target.files.length==0){
                this.changeLoading&&this.changeLoading.close();
                targetEle.removeAttribute('disabled')
                return
            }
            let img1=event.target.files[0];
            let type=img1.type;//文件的类型，判断是否是图片
            let size=img1.size;//文件的大小，判断图片的大小
            this.getAliOSSCreds().then(res => { // 向后台发请求 拉取OSS相关配置
                const Base64 = require('js-base64').Base64;
                const Crypto = require('crypto');
                //因为原来的sha1、hmac、Util文件中 的算法与require直接加载的不同，导致最后的值不同而报405的错误，所以这里沿用 了原来的插件
                const sha1 = require('@/utils/sha1.js');
                const Util = require('@/utils/crypto1.js');
                Crypto.util = Util.util
                Crypto.sha1 = sha1.SHA1
                var returnData = res.result;
                var policyText = {
                    "expiration": "2222-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
                    "conditions": [
                        ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制 10M
                    ]
                };
                var policyBase64 = Base64.encode(JSON.stringify(policyText));
                    console.log(policyBase64)
                    //hmac插件
                    Crypto.HMAC = function(hasher, message, key, options) {
                    // Allow arbitrary length keys
                    key = key.length > hasher._blocksize * 4 ?
                        hasher(key, {
                        asBytes: true
                        }) :
                        Crypto.util.stringToBytes(key);
                    // XOR keys with pad constants
                    var okey = key,
                        ikey = key.slice(0);
                    for (var i = 0; i < hasher._blocksize * 4; i++) {
                        okey[i] ^= 0x5C;
                        ikey[i] ^= 0x36;
                    }
                    var hmacbytes = hasher(Crypto.util.bytesToString(okey) +
                        hasher(Crypto.util.bytesToString(ikey) + message, {
                        asString: true
                        }), {
                        asBytes: true
                        });
                    return options && options.asBytes ? hmacbytes :
                        options && options.asString ? Crypto.util.bytesToString(hmacbytes) :
                        Crypto.util.bytesToHex(hmacbytes);
                };
                var bytes = Crypto.HMAC(Crypto.sha1, policyBase64, res.result.oss_accesskey, {
                    asBytes: true
                });
                var signature = Crypto.util.bytesToBase64(bytes);
                returnData.policy = policyBase64;
                returnData.signature = signature;
                returnData.expire = Date.now() + 600000;
                var type = img1.type == 'video' ? 'video' : 'goods_image';
                var fileNameStr1 = '';
                var fileName = this.getRandomName(img1.name);
                fileNameStr1 = this.getRandomName(fileName);
                if (returnData.app_main_url) {
                    var ossUrl = returnData.oss_host_url + '/' + returnData.app_main_url + '/' + type + '/' + fileNameStr1;
                    var key = returnData.app_main_url + '\/' + type + '\/' + fileNameStr1;
                } else {
                    var ossUrl = returnData.oss_host_url + '/' + type + '/' + fileNameStr1;
                    var key = type + '\/' + fileNameStr1;
                }
                var params = new FormData();
                params.append("key", key);
                params.append("policy", returnData.policy);
                params.append("OSSAccessKeyId", returnData.oss_accessid);
                params.append("success_action_status", '200');
                params.append("signature", returnData.signature);
                params.append("file", img1);
                //设置表头
                let config = {
                headers: {
                    'Accept': 'application/json, text/javascript, */*; q=0.01'
                }
                };
                this.$axios.post(returnData.oss_host_url, params, config).then((res) => {
                    //将base64图片显示到界面
                    var uploadImages = returnData.oss_host_url + '/' + key;
                    this.changeLoading&&this.changeLoading.close();
                    this.bannerList.push(uploadImages);
                    targetEle.removeAttribute('disabled');
                })
            })
        },
        /*
         * 获取oss code
         */
        getAliOSSCreds(){
            return new Promise((resolve,reject)=>{
                this.$http.post({
                    name:'common.upload',
                    data:{
                        invoke_method:'public_page_4m_load_oss_conf'
                    },
                    loading:{
                        enabled:false
                    }
                }).then(({result,response})=>{
                    resolve({result,response});
                }).catch(({msg})=>{
                    reject({msg});
                });
            });
        },
        //处理图片名称
        getRandomName: function(filename) {
            var date = new Date();
            var dateNum = date.getFullYear().toString() + this.formatNum(date.getMonth() + 1) + this.formatNum(date.getDate()) +
            '_' + this.formatNum(date.getHours()) + this.formatNum(date.getMinutes()) + this.formatNum(date.getSeconds());
            var pos = filename.lastIndexOf('.');
            var suffix = '';
            if (pos != -1) {
            suffix = filename.substring(pos)
            }
            return dateNum + this.getRandomString(6) + suffix;
        },
        formatNum: function(number) { //格式化数字
            return Number(number) ? number < 10 ? '0' + number : number : number;
        },
        //获取随机数
        getRandomString: function(len) { //获取随机字符
            var len = len || 32;
            var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
            var maxPos = chars.length;
            var pwd = '';
            for (var i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        }
    },
    beforeDestroy(){
    }
}
</script>
<style lang="less" scoped>
.box{
    padding:0 0.5rem;
    .title{
        font-size:0.8rem;
        line-height:2.6rem;
    }
    .inner{
        .ms-item-upload{
            position:relative;
            margin-right:3%;
            margin-bottom:.43rem;
            width:22.7%;
            height:4.27rem;
            border:1px dashed #e3e3e3;
            &:nth-child(4n){
                margin-right:0;
            }
            .ms-upload-box{
                width:100%;
                height:100%;
                .ms-upload-text{
                    display:block;
                    width:1.28rem;
                    height:1.28rem;
                    background-size:100%;
                    background-position:center;
                    background-repeat:no-repeat;
                    background-image:url(~@/assets/images/img_add_icon.png);
                }
            }
            &.compalte{
                border:1px solid #e3e3e3;
                .ms-upload-box{
                    img{
                        display:block;
                        width:100%;
                        height:100%;
                    }
                    .ms-upload-text{
                        display:none
                    }
                    
                }
                .ms-upload-close{
                        position:absolute;
                        right:0;
                        bottom:0;
                        display:block;
                        width:.85rem;
                        height:.85rem;
                        background-size:100%;
                        background-position:center;
                        background-repeat:no-repeat;
                        background-image:url(~@/assets/images/img_delate_icon.png);
                    }
            }
        }
    }
}

</style>
